package nianbao;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

/**
 * 自定义协议的编码器
 */
public class MessageProtocalToByteEncoder extends MessageToByteEncoder<MessageProtocal> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MessageProtocal messageProtocal, ByteBuf byteBuf) throws Exception {
        //先发送数据长度
        byteBuf.writeInt(messageProtocal.getLength());
        //再发送数据的内容
        byteBuf.writeBytes(messageProtocal.getMessage().getBytes(CharsetUtil.UTF_8));
    }
}
